package actions;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import bean.User;
import dao.UserDAO;

public class LoginAction extends Action{

	boolean loginFailed;
	
	public LoginAction() {
		loginFailed = true;
	}
	
	public String execute(HttpServletRequest request, HttpSession s) throws SQLException, IOException {
		User loginUser = UserDAO.getInstance().checkLogin(new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8"), new String(request.getParameter("password").getBytes("ISO-8859-1"),"UTF-8"));
		String forwardString = null;
		
		if(loginUser != null){
			loginFailed = false;
			if(loginUser.getIsAdmin()){
				forwardString = getForwardProperty("admin");
			}
			else{
				forwardString = getForwardProperty("myPortfolio");
			}
		}
		else{
			loginFailed = true;
			setLoginErrorMessage(s, getMessageProperty("loginFehler"));
			forwardString = getForwardProperty("login");
		}
		
		s.setAttribute("loginFailed", loginFailed);
		if(!loginFailed){
			saveObjectinSession(request, "loginUser", loginUser);
			clearLoginErrorMessage(s);
		}
		
		
		return forwardString;
		
	}
	
	
	public void setLoginErrorMessage(HttpSession s, String message){
		s.setAttribute("loginErrorMessage", message);
	}
	public void clearLoginErrorMessage(HttpSession s){
		s.setAttribute("loginErrorMessage", null);
	}
}
